﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom;
using System.Xaml;
using System.Reflection;
using System.ComponentModel.Composition;

namespace NeuroSpeech.XamlExtensions
{
    [Export]
    public class AttachedPropertyConverter : DefaultConverter
    {
        public override bool CanProcess(
            XamlCodeContext context)
        {
            if (context.Member != null && context.Member.IsAttachable && context.Peek.IsMemberMethod)
                return true;
            return base.CanProcess(context);
        }



        public override CodeStatement Assign(XamlCodeContext context, CodeExpression target, CodeExpression value)
        {
            CodeStatement cs = base.Assign(context,target, value);

            CodeMethodInvokeExpression mi = new CodeMethodInvokeExpression
            {
                Method = new CodeMethodReferenceExpression { 
                    TargetObject = new CodeTypeReferenceExpression(context.Peek.MemberMethod.DeclaringType),
                    MethodName = "Set" + context.Peek.MemberMethod.Name.Substring(3)
                }
            };

            mi.Parameters.Add(context.ParentTarget(target));

            // get methodInfo of "Set"

            // convert...
            //value = TransformToType(context.Peek.MemberMethod.ReturnType, value);
            mi.Parameters.Add(value);

            CodeExpressionStatement ces = new CodeExpressionStatement
            {
                Expression = mi
            };

            return ces;
        }



    }
}
